
const qnyDomain = 'https://apipic.leanplants.com/';
const qnyUploadUrl = 'https://up-z2.qiniup.com/';

// const localDomain = 'http://apiv2.leanplants.com/';
// const uploadUrl = 'http://apiv2.leanplants.com/apicloud/UserManagement.FileLog/uploadFile';
// const localDomain = 'http://192.168.1.201:8081/';
// const uploadUrl = 'http://192.168.1.201:8081/apicloud/UserManagement.FileLog/uploadFile';
const localDomain = 'https://comac-szfj.e.lanxin.cn/samcSixS-php/';
const uploadUrl = 'https://comac-szfj.e.lanxin.cn/samcSixS-php/apicloud/UserManagement.FileLog/uploadFile';
// const localDomain = 'http://jygl.leanplanttec.com:18080/';
// const uploadUrl = 'http://jygl.leanplanttec.com:18080/apicloud/UserManagement.FileLog/uploadFile';
import {http} from '../api/http.js';
import Base64 from './base64.js';
// import md5 from './md5.js';
// import CryptoJS from './crypto-js-4.0.0'
// import CryptoJS from 'crypto-js';
import md5 from 'js-md5';
// var qiniu = require("qiniu");
// import * as qiniu from './qiniu.min.js';

// import compressImage  from './imageutil.js';
let pageList = {};
const $locality = 0;//1 本地部署  默认0 2本地大改动
let util = {
	localDomains(){
		if($locality==0){
			return qnyDomain;
		}else{
			return localDomain;
		}
	},
	toIndex(){
		uni.switchTab({
			url:'/pages/index/index'
		})
	},
	formartDate (){
		const date = new Date()
		const year = date.getFullYear()
		const month = parseInt(date.getMonth()) + 1 > 9 ? parseInt(date.getMonth()) + 1 : '0' + (parseInt(date.getMonth()) + 1)
		const day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
		return year + '-' + month + '-' + day
	},
	timeToTimestamp(time){
		let times = time;
		if(time.indexOf('-')>-1){
			times = time.replace(/-/g,'/');
		}
		let timestamp = new Date(times).getTime();
		return timestamp;
	},
	getNowTime(day,time){
		let date = new Date();
		if(time){
			date = new Date(time*1000);
		}
		let Y = date.getFullYear();
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let D = this.formatNumber(date.getDate());
		let h = this.formatNumber(date.getHours()) + ':';
		let m = this.formatNumber(date.getMinutes()) ;
		let s = this.formatNumber(date.getSeconds());
		if (day == 1) {
			return Y + '年' +M + '月' + D + '日'
		}else if (day == 2) {
			return Y + '年' +M + '月' + D + '日'+' '+ h + m + ':' + s;
		}else if(day == 3){
			return Y+'-' + M +'-'+ D+' '+ h + m + ':' + s;
		}else if(day == 4){
			return h + m + ':' + s;
		}else if(day == 5){
			return Y+'-' + M +'-'+ D+' '+ h + m;
		}else if(day == 6){
			return String(Y) + String(M) + String(D);
		}else {
			return Y +'-' + M +'-'+ D;
		}
	},
	removeLableAndImg(html){
		let msg = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
				.replace(/<br\/?>/gi, '\n').replace(/<[^>/]+>/g, '')
				.replace(/(\n)?<\/([^>]+)>/g, '').replace(/\u00a0/g, ' ')
				.replace(/&nbsp;/g, ' ').replace(/<\/?(img)[^>]*>/gi, '')
				.replace(/&amp;/g, "&").replace(/&lt;/g, "<")
				.replace(/&gt;/g, ">")
				.replace(/&#39;/g, "\'")
				.replace(/&quot;/g, "\"")
				.replace(/<\/?.+?>/g, "")
			return msg
	},
	showLoading (va) {
		uni.showLoading({
			mask:true,
			title: va
		});
	},
	tokenOverdue () {
		uni.showToast({
			title: '请先登录!',
			mask:true,
			icon:'none',
			duration: 2000
		});
		// uni.reLaunch({
		// 	url: '/pages/mycenter/pwdlogin'
		// })
	},
	hideLoading () {
		uni.hideLoading();
	},
	showToast (e,duration=2000) {
		uni.showToast({
			title: e,
			mask:true,
			icon:'none',
			duration
		});
	},
	setStorage (key, val) {
		 uni.setStorageSync(key, val);

		console.log(val);
		// uni.setStorage({
		// 	key: key,
		// 	data: val
		// });
	},
	
	getStorage (key) {
		// let St = '';
		// uni.getStorage({
		// 	key: key,
		// 	success(ret) {
		// 		St = ret.data;
		// 	},
		// 	fail(ret) {
		// 		console.log(ret)
		// 	}
		// });
		console.log(key)
		return uni.getStorageSync(key);
	},
	formatNumber (n){
		n = n.toString()  
		return n[1] ? n : '0' + n  
	},
	timestampToTime (timestamp, day) {
		let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let Y = date.getFullYear() ;
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let D = this.formatNumber(date.getDate());
		let h = this.formatNumber(date.getHours()) ;
		let m = this.formatNumber(date.getMinutes());
		let s = this.formatNumber(date.getSeconds());
		let nowYear = new Date().getFullYear();
		if (day == 1) {
			if(nowYear == Y){
				return M + '月' + D + '日'
			}else{
				return Y + '年' + M + '月' + D + '日'
			}
		}else if(day == 3){
			return Y + '-' + M +'-'+ D+' '+ h + ':'+ m + ':'+ s;
		}else if(day == 4){
			return h + ':'+ m + ':'+ s;
		}else if(day == 5){
			return Y + '.' + M +'.'+ D+' '+ h + ':'+ m + ':'+ s;
		}else if(day == 6){
			return Y + '年' + M + '月' + D + '日'
		}else if(day == 7){
			if(nowYear == Y){
				return M + '.' + D
			}else{
				return Y + '.' + M + '.' + D
			}
		}else if(day == 8){
			return Y + '.' + M + '.' + D
		}else if(day == 9){
			return Y + '/' + M + '/' + D
		}else if(day == 10){
			return Y + '-' + M +'-'+ D+' '+ h + ':'+ m;
		}else if(day == 11){
			return  M +'月'+ D + '日'+' '+ h + ':'+ m;
		}else if(day == 12){
			if(nowYear == Y){
				return M + '.' + D+' '+ h + ':'+ m;
			}else{
				return Y + '.' + M + '.' + D+' '+ h + ':'+ m;
			}
		}else if(day == 13){
			return h + ':'+ m;
		}else {
			return Y + '-' + M +'-'+ D;
		}
	},
	
	change (t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	},
	getSign(){
		let that = this;
		uni.showModal({
			title: '您还未签到',
			content: '是否立即签到?',
			confirmText: '签到',
			confirmColor: '#529eff',
			success: (resl) =>{
				if (resl.confirm) {
					console.log('用户点击确定');
					http('MemberInfo/sign_in').then(res=>{
						uni.showToast({
							title:res.mess,
							icon:'none'
						})
					})
				}
			}
		});
	},
	setServiceContent(name,content){
		let data = {
			name,
			content
		}
		http('memberInfo/saveUserSetting',data).then(res=>{
			
		})
	},
	getServiceContent(name){
		let data = {
			name
		}
		http('memberInfo/getUserSetting',data).then(res=>{
			let content = res.data.value;
			return content;
		})
	},
	gopath (url) {
		
		uni.navigateTo({
			"url": url
		});
	},
	keepTwoDecimalFull (num) {	//四舍五入保留2位小数（不够位数，则用0替补）
		var result = parseFloat(num);
		
		if (isNaN(result)) {
			return false;
		}
		result = Math.round(num * 100) / 100;
		var s_x = result.toString();
		var pos_decimal = s_x.indexOf('.');
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += '.';
		}
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0';
		}
		return s_x;
	},
	getTime (end_time, totalSeconds, type=1) {	// 倒计时
		if (!totalSeconds) {
			// var endDate = new Date(end_time.replace(/-/g, "/"))		// 秒杀结束时间
			var endDate = new Date(end_time)		// 秒杀结束时间
			// var nowDate = new Date();
			var nowDate = Math.round(new Date() / 1000)// 获取当前时间
			// var totalSeconds = parseInt((endDate - nowDate) / 1000)
			var totalSeconds = parseInt(endDate - nowDate)
		}
		
		// 天数（转换成字符串类型，以防网不好的情况下，出现now）
		var day = totalSeconds / (60 * 60 * 24);
		var days=null;
		days = day.toString().split(".")[0];
		// 取模（余数）
		var modulo = totalSeconds % (60 * 60 * 24);
		// 小时数
		var hours = Math.floor(modulo / (60 * 60));
		modulo = modulo % (60 * 60);
		// 分钟
		var minutes = Math.floor(modulo / 60);
		// 秒
		var seconds = modulo % 60;
		
		// 判断时间是否大于10,否则加0
		days = days < 10 ? "0" + days : days;
		hours = hours < 10 ? "0" + hours : hours;
		minutes = minutes < 10 ? "0" + minutes : minutes;
		seconds = seconds < 10 ? "0" + seconds : seconds;
		
		if (type == 1) {
			var time = days+'天'+hours+'时'+minutes+'分'+seconds+'秒';
		} else if (type == 2) {
			var time = days+':'+hours+':'+minutes+':'+seconds;
		}
		
		return time;
	},
	tel (val) {		// 手机号中间四位换成星号
		var tel = "" + val;
		var reg = /^(\d{3})\d{4}(\d{4})$/;
		tel = tel.replace(reg, "$1****$2");
		return tel;
	},
	// const device = uni.getSystemInfoSync();
	// const src = await compressImageHandler(file);
	// async function compressImageHandler(src){
	// 	console.log('platform==='+device.platform)
	// 	const tempPath = await compressImage(src,device.platform);
	// 	console.log('tempPath-----'+tempPath);
	// 	return tempPath
	// }
	// return;
	uploadLocalShangfei:async function(file,callback,fileType='image',modules=0,is_resources=0,task_adviser_log_id=0){//fileType  'video','image',  is_resources 是否顾问上传的资源文件 0不是 1是  2视频号上传的
		console.log('进入',file)
		let userInfo = uni.getStorageSync('userInfo');
		// business3/image/   business3 公司   image/video/other  文件夹
		let business_id = userInfo.business_id?userInfo.business_id:'0';
		let typeName = fileType&&fileType=='video'?'video':'image';
		let fileNamePath = 'business'+business_id+'/'+typeName;
		
		let formartDate = util.formartDate();
		let api_token = md5(`apicloud/UserManagement.FileLog/uploadFile${formartDate}leanplants1234567896s987654159`);
		let token = uni.getStorageSync('token');
		uni.showLoading({
			title:"上传中...",
			mask:true
		});
		var key = "6s_"+new Date().getTime()+'/'+fileNamePath;//图片的随机名字
		let datas = {
			filename: fileNamePath+'/',
			image:file
		}
		http('UserManagement.FileLog/uploadFileBose64',datas).then(res=>{
			console.log('上传',res)
			if(res.status == 200){
				let fileData = res.data.file_name;
				if(is_resources!=1){
					this.upLoadLog(fileData,typeName,modules,is_resources,task_adviser_log_id);
				}
				if(callback) callback(fileData);//回调函数返回路径
			}else{
				uni.showToast({
					title:res.mess,
					icon:'none'
				})
			}
		})
		
		return;
		uni.uploadFile({//上传  七牛云
			url: uploadUrl, //上传的地址
			formData:{
				'filename': fileNamePath+'/',
				'token': token,
				api_token: api_token,
				// business_type:1,//1博雄APP(打包博雄时需要)
				client_id: 1
			},
			name: 'upload',
			success: (res) => {//成功了之后  七牛云上就有这张图  直接七牛域名加key返回去  就行了   如果是传到服务器后台  喊后台返路径就行
			console.log('res');	
			console.log(res);
				uni.hideLoading();
				var data = localDomain + res.data.file_name;//拼接路径
				if(typeof res.data == 'string'){
					data = localDomain + JSON.parse(res.data).data.file_name;
				}
				if(is_resources!=1){
					this.upLoadLog(data,typeName,modules,is_resources,task_adviser_log_id);
				}
				
				if(callback) callback(data);//回调函数返回路径
				if(!data.key){
					// #ifdef H5 || MP-WEIXIN
					if(res.data.mess){
						uni.showToast({
							icon: 'none',
							title: data.mess
						})
					}
					// #endif 
					// #ifdef APP-PLUS
					plus.nativeUI.toast(data.mess)
					// #endif 
				}
			},
			fail:(res)=> {
				uni.hideLoading();
				uni.showToast({
					icon: 'none',
					title: '上传失败'
				})
			}
		});
	},
	uploadLocal:async function(file,callback,fileType='image',modules=0,is_resources=0,task_adviser_log_id=0){//fileType  'video','image',  is_resources 是否顾问上传的资源文件 0不是 1是  2视频号上传的
		console.log(file)
		let userInfo = uni.getStorageSync('userInfo');
		// business3/image/   business3 公司   image/video/other  文件夹
		let business_id = userInfo.business_id?userInfo.business_id:'0';
		let typeName = fileType&&fileType=='video'?'video':'image';
		let fileNamePath = 'business'+business_id+'/'+typeName;
		let comFile;
		// #ifndef H5
		if(fileType=='image'){//压缩图片  可以不传
			uni.compressImage({
			  src: file,
			  quality: 92,
			  success: res => {
			    console.log(res.tempFilePath);
				comFile = res.tempFilePath;
			  }
			})
		}
		// else if(fileType == 'video'){
		// 	uni.compressVideo({
		// 		src: file,
		// 		quality: 'medium',
		// 		success: res => {
		// 			console.log(res.tempFilePath);
		// 			comFile = res.tempFilePath;
		// 		}
		// 	})
		// }
		// #endif
		
		let formartDate = util.formartDate();
		let api_token = md5(`apicloud/UserManagement.FileLog/uploadFile${formartDate}leanplants1234567896s987654159`);
		let token = uni.getStorageSync('token');
		uni.showLoading({
			title:"上传中...",
			mask:true
		});
		var key = "6s_"+new Date().getTime()+'/'+fileNamePath;//图片的随机名字
		
		uni.uploadFile({//上传  七牛云
			url: uploadUrl, //上传的地址
			filePath: comFile?comFile:file,//图片路径  
			formData:{
				'filename': fileNamePath+'/',
				'token': token,
				api_token: api_token,
				// business_type:1,//1博雄APP(打包博雄时需要)
				client_id: 1
			},
			name: 'upload',
			success: (res) => {//成功了之后  七牛云上就有这张图  直接七牛域名加key返回去  就行了   如果是传到服务器后台  喊后台返路径就行
			console.log('res');	
			console.log(res);
				uni.hideLoading();
				var data = localDomain + res.data.file_name;//拼接路径
				if(typeof res.data == 'string'){
					data = localDomain + JSON.parse(res.data).data.file_name;
				}
				if(is_resources!=1){
					this.upLoadLog(data,typeName,modules,is_resources,task_adviser_log_id);
				}
				
				if(callback) callback(data);//回调函数返回路径
				if(!data.key){
					// #ifdef H5 || MP-WEIXIN
					if(res.data.mess){
						uni.showToast({
							icon: 'none',
							title: data.mess
						})
					}
					// #endif 
					// #ifdef APP-PLUS
					plus.nativeUI.toast(data.mess)
					// #endif 
				}
			},
			fail:(res)=> {
				uni.hideLoading();
				uni.showToast({
					icon: 'none',
					title: '上传失败'
				})
			}
		});
	},
	uploadQNY(file,callback,fileType,modules,is_resources,task_adviser_log_id){
		if($locality==0){
			this.uploadQNYDo(file,callback,fileType,modules,is_resources,task_adviser_log_id);
		}else if($locality==2){
			this.uploadLocalShangfei(file,callback,fileType,modules,is_resources,task_adviser_log_id);
		}else{
			this.uploadLocal(file,callback,fileType,modules,is_resources,task_adviser_log_id);
		}
	},
	uploadQNYDo:async function(file,callback,fileType='image',modules=0,is_resources=0,task_adviser_log_id=0){//fileType  'video','image',  is_resources 是否顾问上传的资源文件 0不是 1是  2视频号上传的
		console.log(file)
		let userInfo = uni.getStorageSync('userInfo');
		// business3/image/   business3 公司   image/video/other  文件夹
		let business_id = userInfo.business_id?userInfo.business_id:'0';
		let typeName = fileType&&fileType=='video'?'video':'image';
		let fileNamePath = 'business'+business_id+'/'+typeName+'/';
		let comFile;
		// #ifndef H5
		if(fileType=='image'){//压缩图片  可以不传
			uni.compressImage({
			  src: file,
			  quality: 80,
			  success: res => {
			    console.log(res.tempFilePath);
				comFile = res.tempFilePath;
			  }
			})
		}
		// #endif
		http("Setting/get_qin_token").then(e=>{//请求后台 获取token 上传图片
			if(e.status == 200) {
				uni.showLoading({
					title:"上传中...",
					mask:true
				});
				var key = fileNamePath+"6s_"+new Date().getTime();//图片的随机名字
				
				uni.uploadFile({//上传  七牛云
					url: qnyUploadUrl, //上传的地址
					filePath: comFile?comFile:file,//图片路径  
					formData:{
						'key': key,
						'token': e.data.token
					},
					name: 'file',
					success: (res) => {//成功了之后  七牛云上就有这张图  直接七牛域名加key返回去  就行了   如果是传到服务器后台  喊后台返路径就行
						uni.hideLoading();
						var data = qnyDomain + key;//拼接路径
						if(typeof res.data == 'string'){
							data = qnyDomain + JSON.parse(res.data).key;
						}
						if(is_resources!=1){
							this.upLoadLog(data,typeName,modules,is_resources,task_adviser_log_id);
						}
						
						if(callback) callback(data);//回调函数返回路径
						if(!data.key){
							// #ifdef H5 || MP-WEIXIN
							
							if(res.data.mess){
								uni.showToast({
									icon: 'none',
									title: data.mess
								})
							}
							// #endif 
							// #ifdef APP-PLUS
							plus.nativeUI.toast(data.mess)
							// #endif 
						}
					},
					fail:(res)=> {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '上传失败'
						})
						// console.log(res)
					}
				});
			}
		})
	},
	upLoadLog(datas,typeName,modules=0,is_resources=0,task_adviser_log_id=0){
		let data = {
			file:datas,
			type:typeName=='video'?2:1,
			source:1,
			module:modules,
			is_resources,
			task_adviser_log_id
		}
		http("UserManagement.FileLog/addFileLog",data).then(e=>{
			
		})
	},
	deleteQNY:async function(list){
		// let url = 'http://apipic.leanplants.com/';
		// let reg = new RegExp(url,'g');
		// let names = [];
		// list.forEach(item=>{
		// 	item = item.replace(reg,'');
		// 	names.push(item);
		// })
		// let name = names.join(',');
		// http("Setting/delFile",{name}).then(e=>{
			
		// })
	},
	getRandomStr(){
		let str = String(Math.random()).substr(2,6);
		return str;
	},
	reloadCurrentPage: function(_self, isTab = true) {  
		console.log('arrddd');
		// #ifdef APP-PLUS  
		 console.log(plus.os.name)
		if (plus.os.name === 'iOS') {  
			var route = _self.$scope.route;
			var data = _self.$scope.options && _self.$scope.options.data;
			var url = '/' + route  
			if (data) {  
				url = '/' + route + '?data=' + data  
			}  
			var isRecovery = true;  
			let newTime = Date.now();  
			console.log(newTime)
			if (pageList[url]) { 
				console.log('有pageList[url]--------');
				const query = uni.createSelectorQuery().in(_self);  
				//这里select()中替换为自己的样式class名称  
				query.select('.container_pages').fields({size:true}, data => {  
					isRecovery = false;
				}).exec();  
				setTimeout(() => {  
					if (isRecovery) {  
						console.log('没获取到节点');
						//如果获取不到节点  
						//确保只刷新一次  
						if (newTime - pageList[url] > 3000) {  
							//超过3秒才重新刷新，这里设置几秒就行，目的是防止无限刷新  
							//因为刷新后页面肯定会出来，但是立马再次调用该方法不一定能获取节点  
							pageList[url] = newTime;  
							if (isTab) {  
								uni.reLaunch({  
									url  
								})  
							} else {  
								uni.redirectTo({  
									url  
								})  
							}  
						}
					}  
				}, 600)  
			} else {  
				console.log('没有pageList[url]--------');
				pageList[url] = newTime;  
			} 
		}  
		// #endif  
	},
	bigNumberTransform (value) {
		value = Number(value);
	  const newValue = ['', '', ''];
	  let fr = 1000;
	  let num = 3;
	  let text1 = '';
	  let fm = 1;
	  while (value / fr >= 1) {
	    fr *= 10;
	    num += 1;
	    console.log('数字', value / fr, 'num:', num);
	  }
	 //  if (num <= 4) { // 千
		// newValue[0] = parseFloat(value / 1000).toFixed(2) + '';
	 //    // newValue[0] = parseInt(value / 1000) + '';
	 //    newValue[1] = '千';
	 //  } else 
	  if (num <= 8) { // 万
	    text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万';
	    // tslint:disable-next-line:no-shadowed-variable
	    fm = text1 === '万' ? 10000 : 10000000;
	    if (value % fm === 0) {
	      newValue[0] = parseInt(value / fm) + '';
	    } else {
	      newValue[0] = parseFloat(value / fm).toFixed(1) + '';
	    }
	    newValue[1] = text1;
	  } else if (num <= 16) { // 亿
	    text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
	    text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
	    text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
	    // tslint:disable-next-line:no-shadowed-variable
	    fm = 1;
	    if (text1 === '亿') {
	      fm = 100000000;
	    } else if (text1 === '千亿') {
	      fm = 100000000000;
	    } else if (text1 === '万亿') {
	      fm = 1000000000000;
	    } else if (text1 === '千万亿') {
	      fm = 1000000000000000;
	    }
	    if (value % fm === 0) {
	      newValue[0] = parseInt(value / fm) + '';
	    } else {
	      newValue[0] = parseFloat(value / fm).toFixed(1) + '';
	    }
	    newValue[1] = text1;
	  }
	  if (value < 10000) {
	    newValue[0] = value + '';
	    newValue[1] = '';
	  }
	  return newValue.join('');
	},
	weightLess(arr){
		let result = [];
		let obj = {};
		for(let i = 0;i<arr.length;i++){
			if(!obj[arr[i].accessCode]){
				result.push(arr[i]);
				obj[arr[i].accessCode] = true;
			}
		}
		return result;
	},
	timeToDay(time){
		let days = 86400;
		let day = (time/days).toFixed(2);
		return day;
	},
	previewImg(urls,current,water=2,longPress=1,waterType=1){//water 1益管科技 2姓名+电话 3不带水印  longPress 1不显示长按列表  2默认显示保存图片 waterType 水印样式 1默认 平铺水印  2文字水印 右下角
	// $util.previewImg([item.img],0,2)    $util.previewImg
	// <watermark :water="2"></watermark>  <watermark></watermark>
		let str = '益管科技';
		let userInfo = uni.getStorageSync('userInfo');
		if(userInfo&&water==2){
			str = userInfo.user_name + userInfo.phone;
		}
		let codestr = this.urlsafe_b64encode(str);
		let arr = [];
		urls.map(items=>{
			if(items.indexOf('?imageView2/0/w/100')>-1){
				items = items.replace('?imageView2/0/w/100','');
			}
			let img = '';
			if($locality==2){
				img = this.localDomains() + items;
			}else{
				if(items.indexOf('?vframe/jpg/offset/1')>-1){
					img = items;
				}else{
					if(water == 3){
						img = items;
					}else{
						img = items + '?watermark/4/text/'+codestr+'/fontsize/1400/fill/Z3JheQ==/dissolve/35/rotate/-20/uw/980/uh/380/resize/1';
					}
				}
			}
			// if(waterType == 2){
			// 	img = items + '?watermark/2/text/'+codestr+'/fontsize/1400/fill/Z3JheQ==/dissolve/35/rotate/-20/uw/980/uh/380/resize/1';
			// }
			arr.push(img);
			// items =  items +'?watermark/2/text/5LiD54mb5LqR5a2Y5YKo/fontsize/400';
			// console.log(items + '?watermark/4/text/'+codestr+'/fontsize/800/fill/Z3JheQ==/dissolve/30/rotate/-20/uw/300/uh/200/resize/1')
		})
		setTimeout(()=>{
			if(longPress==1){
				uni.previewImage({
					current,
					urls:arr,
					longPressActions: {
						itemList: [],
						success: function(data) {
							
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			}else{
				uni.previewImage({
					current,
					urls:arr
				})
			}
		})
	},
	addVideoWater:async function(file,callback,fileType='image',modules=0,is_resources=0){//fileType  'video','image',  is_resources 是否顾问上传的资源文件 0不是 1是  2视频号上传的
		let userInfo = uni.getStorageSync('userInfo');
		// business3/image/   business3 公司   image/video/other  文件夹
		let business_id = userInfo.business_id?userInfo.business_id:'0';
		let typeName = fileType&&fileType=='video'?'video':'image';
		let fileNamePath = 'business'+business_id+'/'+typeName+'/';
		
		http("Setting/get_qin_token").then(e=>{//请求后台 获取token 上传图片
			if(e.status == 200) {
				uni.showLoading({
					title:"上传中...",
					mask:true
				});
				var key = fileNamePath+"6s_"+new Date().getTime();//图片的随机名字
				let tokens = e.data.token;
				const putExtra = {
					fname: file.name,
				};
				// let watermark = 'https://apipic.leanplants.com/water/app_watermark.png';
				// let codestr = this.urlsafe_b64encode(watermark);
				
				// let vUrl = `${url}/avthumb/h264/wmImage/${codestr}`;
				
				// , putExtra, config
				const observable = qiniu.upload(file, key, tokens,putExtra)
				console.log(observable)
				setTimeout(()=>{
					const subscription = observable.subscribe(observer=>{
						console.log(observer)
						uni.hideLoading();
					}) // 上传开始
					console.log(subscription)
				})
				
				// or
				// const subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以
				// subscription.unsubscribe() // 上传取消
				// uni.uploadFile({//上传  七牛云
				// 	url: qnyUploadUrl, //上传的地址
				// 	filePath: comFile?comFile:file,//图片路径  
				// 	formData:{
				// 		'key': key,
				// 		'token': e.data.token
				// 	},
				// 	name: 'file',
				// 	success: (res) => {//成功了之后  七牛云上就有这张图  直接七牛域名加key返回去  就行了   如果是传到服务器后台  喊后台返路径就行
				// 		uni.hideLoading();
				// 		var data = qnyDomain + key;//拼接路径
				// 		if(typeof res.data == 'string'){
				// 			data = qnyDomain + JSON.parse(res.data).key;
				// 		}
				// 		if(is_resources!=1){
				// 			this.upLoadLog(data,typeName,modules,is_resources);
				// 		}
						
				// 		if(callback) callback(data);//回调函数返回路径
				// 		if(!data.key){
				// 			// #ifdef H5 || MP-WEIXIN
							
				// 			if(res.data.mess){
				// 				uni.showToast({
				// 					icon: 'none',
				// 					title: data.mess
				// 				})
				// 			}
				// 			// #endif 
				// 			// #ifdef APP-PLUS
				// 			plus.nativeUI.toast(data.mess)
				// 			// #endif 
				// 		}
				// 	},
				// 	fail:(res)=> {
				// 		uni.hideLoading();
				// 		uni.showToast({
				// 			icon: 'none',
				// 			title: '上传失败'
				// 		})
				// 		// console.log(res)
				// 	}
				// });
			}
		})
	},
	// 字符串转base64
	baseToa(str) {
	  // 对字符串进行编码
	  var encode = encodeURI(str)
	  // 对编码的字符串转化base64
	  var base64 = btoa(encode)
	  return base64
	},
	// base64转字符串
	strTob(base64) {
	  // 对base64转编码
	  var decode = atob(base64)
	  // 编码转字符串
	  var str = decodeURI(decode)
	  return str
	},
	urlsafe_b64encode(str) {
		
		// 将字符串转换为 UTF-8 编码的字节数组
		  // let utf8Bytes = new TextEncoder().encode(str);
		
		  // 将字节数组转换为 Base64 编码的字符串
		  // let base64Str = btoa(String.fromCharCode(...utf8Bytes));
		let base64Str = Base64.encode(str);
		  // 按照 Base64 编码规则，它会被编码为 "SGVsbG8=". 注意末尾的 "=" 补位符。
		  // 如果使用 URL 安全的 Base64 编码，它会被编码为 "SGVsbG8"，没有补位符。在解码时，需要根据编码时使用的方式来添加或去掉补位符。
		  // 替换不安全的字符并去掉补位符
		  return base64Str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
	},
	urlsafe_b64decode(encodedStr) {
		// 添加补位符并替换安全的字符
		  encodedStr = encodedStr.replace(/-/g, "+").replace(/_/g, "/");
		  // 在这里使用 while 循环的原因是为了确保添加的补位符数量正确。
		  // 因为在某些情况下，需要添加多个 "=" 补位符，而使用 if 语句只能添加一个 "="。比如，如果编码后的字符串长度为 2，那么需要添加两个 "=" 补位符，才能使字符串长度变为 4。
		  while (encodedStr.length % 4) {
		   encodedStr += "=";
		  }
		
		  // 将 Base64 编码的字符串转换为字节数组
		  let base64Bytes = Uint8Array.from(atob(encodedStr), (c) => c.charCodeAt(0));
		
		  // 将字节数组转换为 UTF-8 编码的字符串
		  return new TextDecoder().decode(base64Bytes);
	},
	// 获取浮点数的小数位数
	getPrecision(num) {
	  const str = String(parseFloat(num));
	  const decimalIndex = str.indexOf('.');
	  return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
	},
	// 加法运算
	add(a, b) {
	  const precision = Math.max(this.getPrecision(a), this.getPrecision(b));
	  const multiplier = Math.pow(10, precision);
	  return (Math.round(a * multiplier) + Math.round(b * multiplier)) / multiplier;
	},
	// 减法运算
	subtract(a, b) {
	  return this.add(a, -b);
	},
	
	// 乘法运算
	multiply(a, b) {
	  const precision = this.getPrecision(a) + this.getPrecision(b);
	  const multiplier = Math.pow(10, precision);
	  return (Math.round(a * multiplier) * Math.round(b * multiplier)) / (multiplier * multiplier);
	},
	
	// 除法运算
	divide(a, b) {
	  // const precision = this.getPrecision(a) - this.getPrecision(b);
	  // const divisor = Math.pow(10, precision);
	  // return (Math.round(a / b * divisor)) / divisor;
	  var r1=0,r2=0,t1,t2;
	  r1=Number(a.toString().replace('.',''));
	  r2=Number(b.toString().replace('.',''));
	  t1 = a.toString().split('.')[1]?a.toString().split('.')[1].length:0;
	  t2 = b.toString().split('.')[1]?b.toString().split('.')[1].length:0;
	  let result = (r1/r2) * Math.pow(10,t2-t1);
	  return result.toString().split('.')[1]&&result.toString().split('.')[1].length>3?result.toFixed(3):result
	},
	shareMiniProgram(item,resource_type=1){
		let imageUrl = 'https://www.leanplanttec.com/static/20240511153230.png';
		if(item.video_url){
			imageUrl = item.video_url+'?vframe/jpg/offset/1/imageView2/0/w/300';
		}
		if(item.img_url_arr&&item.img_url_arr.length){
			imageUrl = item.img_url_arr[0]+'?imageView2/0/w/300';
		}
		let id = item.id;
		uni.share({
		    provider: 'weixin',
		    scene: "WXSceneSession",
		    type: 5,
		    imageUrl,
		    title: item.introduce,
		    miniProgram: {
		        id: 'gh_67430049a97c',
		        path: 'pageVideo/video/detail?shareType=2&id='+id+'&resource_type='+resource_type,
		        type: 0,
		        webUrl: 'http://api.leanplants.com'
		    },
		    success: ret => {
		        console.log(JSON.stringify(ret));
		    }
		});
	},
	shareCircle(item){
		let imageUrl = 'https://www.leanplanttec.com/static/20240511153230.png';
		if(item.video_url){
			imageUrl = item.video_url+'?vframe/jpg/offset/1/imageView2/0/w/300';
		}
		if(item.img_url_arr&&item.img_url_arr.length){
			imageUrl = item.img_url_arr[0]+'?imageView2/0/w/300';
		}
		let id = item.id;
		uni.share({
			provider: "weixin",
			scene: "WXSceneTimeline",
			type: 0,
			href: item.url,
			title: item.introduce,
			summary: item.details,
			imageUrl,
			success: function (res) {
				console.log("success:" + JSON.stringify(res));
			},
			fail: function (err) {
				console.log("fail:" + JSON.stringify(err));
			}
		});
	},
	checkPermission() {//title，权限未开启提示的消息
	    return new Promise((resolve) => {
	        plus.android.requestPermissions(
	            ["android.permission.ACCESS_FINE_LOCATION"],
	            function (resultObj) {
					console.log(resultObj)
	                if (resultObj.granted.length < 1) { //resultObj.granted是授权的权限，是一个数组，你可以直接判断长度也可以拿出来单独判断
	                  // uni.showToast({
	                  //       icon: "none",
	                  //       title,
	                  //   });
	                    resolve(false)
	                    // let timer1 = setTimeout(() => { //没有开对应的权限，打开app的系统权限管理页
	                    //     var Intent = plus.android.importClass("android.content.Intent");
	                    //     var Settings = plus.android.importClass("android.provider.Settings");
	                    //     var Uri = plus.android.importClass("android.net.Uri");
	                    //     var mainActivity = plus.android.runtimeMainActivity();
	                    //     var intent = new Intent();
	                    //     intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
	                    //     var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
	                    //     intent.setData(uri);
	                    //     mainActivity.startActivity(intent);
	                    //     clearTimeout(timer1)
	                    //     timer1 = null
	                    // }, 1000)
	                } else {
	                    resolve(true)
	                }
	            }
	        );
	    })
	},
	randomNum(){
		let num = '';
		let date = new Date();
		let Y = date.getFullYear();
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let D = this.formatNumber(date.getDate());
		let str = Math.random().toString().slice(2,6);
		num = `${Y}${M}${D}${str}`;
		return num
	},
}

export default util
